package posts

import (
	"context"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/resultx"
	"mall/service/forum/model"
	"mall/service/forum/rpc/internal/svc"
	"mall/service/forum/rpc/types/forum"

	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePostLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePostLogic {
	return &UpdatePostLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePostLogic) UpdatePost(in *forum.PostsInfo) (*forum.BaseResp, error) {
	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, err
	}

	if len(in.Ids) > 0 { // 批量修改状态
		now := time.Now()
		for _, id := range in.Ids {
			if id > 0 && in.Status != nil {
				post, err := l.svcCtx.Post.FindOneNoCache(l.ctx, tx, id)
				if err != nil {
					tx.Rollback()
					return nil, err
				}

				post.PostStatus = uint8(*in.Status)
				post.PostModifiedDate = now
				err = l.svcCtx.Post.Update(l.ctx, tx, post, nil)
				if err != nil {
					tx.Rollback()
					return nil, err
				}
			}
		}

		tx.Commit()

		return &forum.BaseResp{}, nil
	}

	if in.Id == nil || *in.Id == 0 {
		return nil, resultx.StatusError(resultx.FORUM_POST_ID_REQUIRED, "")
	}

	if in.AuthorId == nil || *in.AuthorId == 0 {
		return nil, resultx.StatusError(resultx.FORUM_POST_AUTHOR_ID_INVALID, "")
	}

	var skipMeta bool
	if in.SkipMeta != nil && *in.SkipMeta > 0 {
		skipMeta = true
	}
	var skipMedia bool
	if in.SkipMedia != nil && *in.SkipMedia > 0 {
		skipMedia = true
	}
	var skipContent bool
	if in.SkipContent != nil && *in.SkipContent > 0 {
		skipContent = true
	}

	if !skipContent && (in.PostContent == nil || len(strings.TrimSpace(*in.PostContent)) == 0) {
		return nil, resultx.StatusError(resultx.FORUM_POST_CONTENT_REQUIRED, "")
	}

	post, err := l.svcCtx.Post.FindOneNoCache(l.ctx, nil, *in.Id)
	if err != nil {
		return nil, err
	}

	if post.PostAuthorID != *in.AuthorId {
		return nil, resultx.StatusError(resultx.FORUM_POST_AUTHOR_ID_INVALID, "")
	}

	if post.PostStatus == uint8(globalkey.StatusDeleted) || post.PostStatus == uint8(globalkey.StatusApproved) {
		return nil, resultx.StatusError(resultx.FORUM_POST_STATUS_INVALID, "")
	}

	pid := post.PostID
	if !skipContent {
		post.PostContent = strings.TrimSpace(*in.PostContent)
	}
	post.PostModifiedDate = time.Now()

	if in.AuthorNickname != nil && len(strings.TrimSpace(*in.AuthorNickname)) > 0 {
		post.PostAuthorNickname = strings.TrimSpace(*in.AuthorNickname)
	}
	if in.AuthorAvatar != nil && len(strings.TrimSpace(*in.AuthorAvatar)) > 0 {
		post.PostAuthorAvatar = strings.TrimSpace(*in.AuthorAvatar)
	}
	if in.AuthorIP != nil && len(strings.TrimSpace(*in.AuthorIP)) > 0 {
		post.PostAuthorIP = strings.TrimSpace(*in.AuthorIP)
	}
	if in.AuthorRankId != nil && *in.AuthorRankId > 0 {
		post.PostAuthorRankID = uint8(*in.AuthorRankId)
	}
	if in.AuthorRoleId != nil && *in.AuthorRoleId > 0 {
		post.PostAuthorRoleID = uint8(*in.AuthorRoleId)
	}
	if in.AuthorAnonymous != nil && *in.AuthorAnonymous > 0 {
		post.PostAuthorAnonymous = 1
	}
	if in.PostTitle != nil && len(strings.TrimSpace(*in.PostTitle)) > 0 {
		post.PostTitle = strings.TrimSpace(*in.PostTitle)
	}
	if in.Status != nil {
		post.PostStatus = uint8(*in.Status)
	}
	if in.CommentStatus != nil {
		if *in.CommentStatus > 0 {
			post.CommentStatus = 1
		} else {
			post.CommentStatus = 0
		}
	}

	rel := &model.ForumPostRel{}
	if skipContent {
		rel.Blacklist = append(rel.Blacklist, model.ForumPostColumns.PostContent)
		rel.Blacklist = append(rel.Blacklist, model.ForumPostColumns.PostContentFiltered)
	}

	var thumbnailIdMetaId uint64
	var thumbnailUrlMetaId uint64
	var photoCountMetaId uint64
	if !skipMeta {
		metaFilterMap := make(map[string]map[string][]any)
		metaFilterMap[model.ForumPostMetumColumns.PostID] = map[string][]any{
			"equalTo": {pid},
		}
		list, _, err := l.svcCtx.Post.GetMeta(l.ctx, model.M{}, -1, metaFilterMap)
		if err != nil {
			return nil, err
		}

		if len(list) > 0 { // 原有的 Meta（决定现有的是增还是改）
			var omids []uint64
			omidMap := make(map[uint64]struct{})
			for _, v := range list {
				if len(v.MetaKey) > 0 && v.MetaValue.Valid {
					switch v.MetaKey { // 先排除特殊Key
					case "_thumbnail_id":
						thumbnailIdMetaId = v.MetaID
					case "_thumbnail_url":
						thumbnailUrlMetaId = v.MetaID
					case "_photo_count":
						photoCountMetaId = v.MetaID
					case "_view_count":
					case "_comment_count":
					case "_forward_count":
					default:
						omids = append(omids, v.MetaID)
						omidMap[v.MetaID] = struct{}{}
					}
				}
			}

			// 现有的 Meta（决定原有的是删还是留）
			nmidMap := make(map[uint64]struct{})
			if len(in.Meta) > 0 {
				for _, v := range in.Meta {
					if v.Key == nil || len(strings.TrimSpace(*v.Key)) == 0 {
						continue
					}

					if v.Value == nil || len(strings.TrimSpace(*v.Value)) == 0 {
						continue
					}

					var metum model.ForumPostMetum
					metum.PostID = pid
					metum.MetaKey = strings.TrimSpace(*v.Key)
					metum.MetaValue = null.StringFrom(strings.TrimSpace(*v.Value))

					if v.Id != nil && *v.Id > 0 {
						if _, ok := omidMap[*v.Id]; ok { // 有值且是有效值，为修改，否则为新增
							nmidMap[*v.Id] = struct{}{}
							metum.MetaID = *v.Id
						}
					}

					rel.Meta = append(rel.Meta, &metum)
				}
			}

			for _, mid := range omids {
				if _, ok := nmidMap[mid]; !ok { // 当前不存在的值，应该删除
					rel.DelMetaIds = append(rel.DelMetaIds, mid)
				}
			}
		} else if len(in.Meta) > 0 { // 不存在原值，则都是新增
			for _, v := range in.Meta {
				if v.Key == nil || len(strings.TrimSpace(*v.Key)) == 0 {
					continue
				}

				if v.Value == nil || len(strings.TrimSpace(*v.Value)) == 0 {
					continue
				}

				var metum model.ForumPostMetum
				metum.PostID = pid
				metum.MetaKey = strings.TrimSpace(*v.Key)
				metum.MetaValue = null.StringFrom(strings.TrimSpace(*v.Value))

				rel.Meta = append(rel.Meta, &metum)
			}
		}
	}

	if !skipMedia {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.ForumAttachmentRelationshipColumns.ObjectID] = map[string][]any{
			"equalTo": {pid},
		}
		filterMap[model.ForumAttachmentRelationshipColumns.ObjectType] = map[string][]any{
			"equalTo": {globalkey.AttachmentLogTypeForumPost},
		}
		list, _, err := l.svcCtx.Post.GetMedia(l.ctx, model.M{}, -1, filterMap)
		if err != nil {
			return nil, err
		}

		mediaUidMap := make(map[uint64]*model.ForumAttachmentRelationship)
		if len(list) > 0 {
			for _, v := range list {
				mediaUidMap[v.AttachmentRelationshipID] = v
			}
		}

		if len(in.NewMedia) > 0 {
			var thumbnailOrder uint
			var thumbnailId uint64
			var thumbnailUrl string
			for idx, v := range in.NewMedia {
				var url string
				if v.Url != nil && len(*v.Url) > 0 { // v.Uri  content版本（包含?id）  v.Url  url当前版本 | attachment当前版本
					url = *v.Url
				}
				var uri string
				if v.Uri != nil && len(*v.Uri) > 0 {
					uri = *v.Uri
					if len(url) == 0 {
						url = uri
					}
				}
				if len(url) == 0 {
					continue
				}

				var thumbnail uint8
				if v.Thumbnail != nil && *v.Thumbnail > 0 {
					thumbnail = uint8(*v.Thumbnail)
				}
				var order uint
				if v.Order != nil {
					order = uint(*v.Order)
				} else {
					order = uint(idx) + globalkey.AttachmentOrderOffset
				}
				var altText string
				if v.AltText != nil && len(*v.AltText) > 0 {
					altText = *v.AltText
				}
				var meta []string
				if v.Name != nil && len(*v.Name) > 0 {
					meta = append(meta, "filename:"+*v.Name)
					if len(altText) == 0 {
						altText = *v.Name
					}
				}
				if v.MetaData != nil && len(*v.MetaData) > 0 {
					meta = append(meta, *v.MetaData)
				}
				if v.MimeType != nil && len(*v.MimeType) > 0 {
					meta = append(meta, "mimeType:"+*v.MimeType)
				}
				metaData := strings.Join(meta, ";")

				var mediaId uint64
				if v.Id != nil && len(*v.Id) > 0 {
					if i, err := strconv.ParseInt(*v.Id, 10, 64); err == nil {
						mediaId = uint64(i)
					}
				}
				var uid uint64
				if v.Uid != nil && *v.Uid > 0 {
					uid = *v.Uid
				}

				if uid > 0 { // 原有缩略图
					if _, ok := mediaUidMap[uid]; ok { // 存在，修改，否则无效
						delete(mediaUidMap, uid)
						rel.Media = append(rel.Media, &model.ForumAttachmentRelationship{
							AttachmentRelationshipID: uid,
							AttachmentID:             mediaId,
							AttachmentThumbnail:      thumbnail,
							AttachmentOrder:          order,
							AttachmentImageURL:       url,
							AttachmentImageAlt:       altText,
							AttachmentImageMeta:      metaData,
						})
					}
					continue
				}

				media := &model.ForumAttachmentRelationship{
					AttachmentID:        mediaId,
					AttachmentThumbnail: thumbnail,
					AttachmentOrder:     order,
					AttachmentImageURL:  url,
					AttachmentImageAlt:  altText,
					AttachmentImageMeta: metaData,
				}

				rel.Media = append(rel.Media, media)
			}

			for _, v := range rel.Media {
				if v.AttachmentThumbnail > 0 && (len(thumbnailUrl) == 0 || thumbnailOrder > v.AttachmentOrder) { // thumbnailOrder尚未赋值，或当前值更小
					thumbnailOrder = v.AttachmentOrder
					thumbnailId = v.AttachmentID
					thumbnailUrl = v.AttachmentImageURL
				}
			}

			if len(thumbnailUrl) > 0 {
				rel.Meta = append(rel.Meta, &model.ForumPostMetum{
					MetaID:    thumbnailIdMetaId,
					MetaKey:   "_thumbnail_id",
					MetaValue: null.StringFrom(strconv.FormatInt(int64(thumbnailId), 10)),
				})
				rel.Meta = append(rel.Meta, &model.ForumPostMetum{
					MetaID:    thumbnailUrlMetaId,
					MetaKey:   "_thumbnail_url",
					MetaValue: null.StringFrom(thumbnailUrl),
				})
			}
			rel.Meta = append(rel.Meta, &model.ForumPostMetum{
				MetaID:    photoCountMetaId,
				MetaKey:   "_photo_count",
				MetaValue: null.StringFrom(strconv.FormatInt(int64(len(rel.Media)), 10)),
			})
		}

		for _, v := range mediaUidMap {
			rel.DelMediaIds = append(rel.DelMediaIds, v.AttachmentRelationshipID)
		}
	}

	err = l.svcCtx.Post.Update(l.ctx, tx, post, rel)
	if err != nil {
		tx.Rollback()
		return nil, err
	}

	tx.Commit()

	return &forum.BaseResp{}, nil
}
